package com.tongda.menu.adapter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tongda.core.common.Constants;
import com.tongda.core.service.DishService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.MenuDBHelper;
import com.tongda.core.vo.Dish;
import com.tongda.menu.R;
import com.tongda.menu.R.drawable;
import com.tongda.menu.activity.IntroduceActivity;
import com.tongda.menu.activity.MainActivity;
import com.tongda.menu.activity.RstNewsActivity;
import com.tongda.menu.activity.RstStateActivity;
import com.tongda.menu.util.ActivityMenuUtil;
import com.tongda.menu.widget.CircleImageView;
import com.tongda.menu.widget.RoundImageView;

public class WaterfallAdapter extends BaseAdapter {
	private static final int INTRO_POSITION = 0;// 餐厅简介的坐标
	private static final int NEWS_POSITION = 1;// 餐厅动态的坐标
	private static final int HELP_POSITION = 2;// 使用帮助的坐标
	List<Dish> list;
	Context context;

	public WaterfallAdapter(List<Dish> list, Context context) {
		this.list = list;
		this.context = context;

	}

	@Override
	public int getCount() {
		return list != null ? list.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(final int position, View convertView, ViewGroup group) {
		final Holder holder;
		if (convertView == null) {
			holder = new Holder();
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(R.layout.item_sample, null);

			holder.image = (RoundImageView) convertView
					.findViewById(R.id.thumbnail);
			holder.viewbg = (RelativeLayout) convertView
					.findViewById(R.id.card_list);
			holder.ly = (RelativeLayout) convertView
					.findViewById(R.id.main_rst_ly);
			holder.tv = (TextView) convertView
					.findViewById(R.id.main_item_dishName);
			holder.dishCfBtn = (Button) convertView
					.findViewById(R.id.main_item_confirm);
			holder.dishSPriceTv = (TextView) convertView
					.findViewById(R.id.main_item_dishSprice);
			holder.dishPriceTv = (TextView) convertView
					.findViewById(R.id.main_item_dishprice);
			holder.dishIconzpImv = (ImageView) convertView
					.findViewById(R.id.main_item_icon_zhaopai);
			holder.dishIcontjianImv = (ImageView) convertView
					.findViewById(R.id.main_item_icon_tuijian);
			holder.dishIcontjiaImv = (ImageView) convertView
					.findViewById(R.id.main_item_icon_tejia);
			holder.dishIconsjImv = (ImageView) convertView
					.findViewById(R.id.main_item_icon_shijia);
			holder.dishStopImv = (ImageView) convertView
					.findViewById(R.id.main_item_stopsell);
			holder.dishOrderNumTv = (TextView) convertView
					.findViewById(R.id.main_item_orderNum);
			holder.rst_icon = (ImageView) convertView
					.findViewById(R.id.main_rst_icon);
			holder.rst_tv = (TextView) convertView
					.findViewById(R.id.main_rst_tv);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}

		if (list.size() == 0) {
			return convertView;
		}
		final Dish data = list.get(position);
		// holder.image.setDrawingCacheEnabled(false);

		String url = "";
		if (data.getLowpicUrls() != null && data.getLowpicUrls().size() > 0
				&& !data.getLowpicUrls().contains(null)) {
			url = data.getLowpicUrls().get(0);
		} else {
			url = "";
		}
		ActivityMenuUtil.loadImage(((MainActivity) (context)).imageLoader,
				Constants.BASE_SERVIER_URLS + url, holder.image,
				((MainActivity) (context)).options, context);

		if (((MainActivity) context).dishCurrentPosition == position) {
			holder.viewbg.setBackgroundResource(drawable.main_selected);
		} else {
			holder.viewbg.setBackgroundResource(drawable.main_unselected);
		}

		if (position == INTRO_POSITION||position == NEWS_POSITION||position == HELP_POSITION) {
			holder.ly.setVisibility(View.VISIBLE);
			if (position == INTRO_POSITION) {
				holder.rst_icon.setBackgroundResource(R.drawable.rst_intro);
				holder.rst_tv.setText("餐厅简介");
			} else if (position == NEWS_POSITION) {
				holder.rst_icon.setBackgroundResource(R.drawable.rst_news);
				holder.rst_tv.setText("餐厅动态");
			} else if (position == HELP_POSITION) {
				holder.rst_icon.setBackgroundResource(R.drawable.rst_help);
				holder.rst_tv.setText("使用帮助");
			} 
		} else {
			holder.ly.setVisibility(View.GONE);
		}

		holder.ly.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (position == INTRO_POSITION) {
					ActivityUtil.switchActivity((MainActivity) context, false,
							RstNewsActivity.class);
				} else if (position == NEWS_POSITION) {
					ActivityUtil.switchActivity(((MainActivity) context),
							false, RstStateActivity.class);
				} else if (position == HELP_POSITION) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("from", "Help");
					ActivityUtil.switchActivity(((MainActivity) context),
							false, IntroduceActivity.class, params);
				}
				((MainActivity) context).overridePendingTransition(
						R.anim.in_from_top, R.anim.out_to_bottom);
			}
		});

		holder.tv.setText(String.valueOf(data.getDishesName()));
		holder.image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				((MainActivity) context).dishCurrentPosition = position;
				if (((MainActivity) context).dishCategory_util
						.init4DishesCategory().size() > 0) {
					if (((MainActivity) context).flag) {
						((MainActivity) context).showMenuShowActivity(
								data.getCategoryId(), position);
					} else {
						if (!((MainActivity) context).isClicked) {
							((MainActivity) context).dishCategoryId = "all";
						}
						((MainActivity) context).showMenuShowActivity(
								((MainActivity) context).dishCategoryId,
								position);
					}
				} else {
					((MainActivity) context).showMenuShowActivity(
							((MainActivity) context).dishCategoryId, position);
				}

			}
		});

		/*
		 * 处理已点份数
		 */
		if (data.getDishorderNum() > 0) {
			Typeface typeFace = Typeface.createFromAsset(
					((MainActivity) context).getAssets(), "hwcy.ttf");
			holder.dishOrderNumTv.setTypeface(typeFace);
			holder.dishOrderNumTv.setTextColor(((MainActivity) context)
					.getResources().getColor(R.color.light_brown));
			holder.dishOrderNumTv.setText("x "
					+ String.valueOf(data.getDishorderNum()));
		} else {
			holder.dishOrderNumTv.setText("");
		}

		holder.dishCfBtn.setOnClickListener(new OnClickListener() {

			@SuppressLint("SimpleDateFormat")
			@Override
			public void onClick(View v) {

				final Handler handler = new Handler() {
					private SQLiteDatabase db = context.openOrCreateDatabase(
							MenuDBHelper.DATABASE_NAME, Context.MODE_PRIVATE,
							null);

					@Override
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						if (((MainActivity) (context)).bound) {
							((MainActivity) (context)).soundService.playSound();
						}
						// ((MainActivity)(context)).sp.play(((MainActivity)(context)).music,
						// 1, 1, 0, 0, 1);
						((MainActivity) context).dishCurrentPosition = position;

						// 如果不在特价时段内，重新定义特价就是原价，插入购物车列表
						if (msg.getData().getString("priceStr").equals("null")) {
							data.setSpecialPrice(data.getPrice());
						}
						// 根据该菜肴是不是套餐进行不同的处理，是套餐的话就加一条，不是套餐的话如果没有就加一套，否则加个数
						if (data.getIsSet().equals("true")
								&& data.getDsDishes() != null
								&& data.getDsDishes().size() > 0) {
							((MainActivity) context).ordered_dish_dao.insert(
									data, ((MainActivity) context).dish_util,
									((MainActivity) context).TABLE_NAME,
									context);
							((MainActivity) context).dish_dao.updateAddNum(
									data.getDishesId(), 1);
						} else {
							int orderNum = ((MainActivity) context).ordered_dish_dao
									.getNum(data.getDishesId());
							if (orderNum == 0) {
								((MainActivity) context).ordered_dish_dao
										.insert(data,
												((MainActivity) context).dish_util,
												((MainActivity) context).TABLE_NAME,
												((MainActivity) context));
							} else {
								++orderNum;
								((MainActivity) context).ordered_dish_dao
										.updateNum(data.getDishesId(), orderNum);
							}
						}

						// 改变一级菜类的点菜数量
						String categoryLevel = ((MainActivity) context).dishCategory_dao
								.getCategoryLevel(context, data.getCategoryId());
						String dcIdStr = data.getCategoryId();
						if (categoryLevel.equals("2")) {
							dcIdStr = ((MainActivity) context).dishCategory_dao
									.getparentCategoryId(dcIdStr);
						}
						for (int i = 0; i < ((MainActivity) context).dishCategoryDatas
								.size(); i++) {
							if (dcIdStr
									.equals(((MainActivity) context).dishCategoryDatas
											.get(i).getCategoryId())) {
								int num = ((MainActivity) context).dishCategoryDatas
										.get(i).getDishNum();
								num++;
								((MainActivity) context).dishCategoryDatas.get(
										i).setDishNum(num);
								break;
							}
						}

						/*
						 * 处理菜肴的已点份数
						 */
						int dishorderNum = data.getDishorderNum();
						dishorderNum++;
						data.setDishorderNum(dishorderNum);
						/*
						 * 处理已点份数
						 */
						if (data.getDishorderNum() > 0) {
							Typeface typeFace = Typeface.createFromAsset(
									((MainActivity) context).getAssets(),
									"hwcy.ttf");
							holder.dishOrderNumTv.setTypeface(typeFace);
							holder.dishOrderNumTv
									.setTextColor(((MainActivity) context)
											.getResources().getColor(
													R.color.light_brown));
							holder.dishOrderNumTv.setText("x "
									+ String.valueOf(data.getDishorderNum()));
						} else {
							holder.dishOrderNumTv.setText("");
						}

						((MainActivity) context).dish_dao.updateNum(
								data.getDishesId(), dishorderNum);

						if (categoryLevel.equals("2")) {
							((MainActivity) context).subCategoryId = data
									.getCategoryId();
						}
						if (!((MainActivity) context).subCategoryId.equals("")) {
							((MainActivity) context).updatedcDishNum(
									((MainActivity) context).subCategoryId, db);
							if (((MainActivity) context).flag) {
								((MainActivity) context).updatesubCategory();
							}
						}
						int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
						holder.image.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
						CircleImageView buyImg = new CircleImageView(context);
						buyImg.setBackgroundResource(R.drawable.scroll);
						((MainActivity) context).setAnim(buyImg,
								start_location, 0);// 开始执行动画
						// }
					}
				};
				// 判断该菜肴是否在特价时段内并根据结果处理菜肴的价格显示。
				Thread judgePriceThread = new Thread(new Runnable() {

					private String priceStr = "";

					@Override
					public void run() {
						Message msg = handler.obtainMessage();
						if (data.getSpecialPrice() != null
								&& ActivityMenuUtil.checkNetworkState(context)) {
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyy-MM-dd HH:MM:ss");
							String creatTimeStr = format.format(new Date());
							BigDecimal price = DishService.judgePrice(
									data.getDishesId(), data.getIsSet(),
									creatTimeStr);
							priceStr = price + "";
						}
						Bundle bundle = new Bundle();
						bundle.putString("priceStr", priceStr);
						msg.setData(bundle);
						handler.sendMessage(msg);
					}
				});
				if (!((MainActivity) context).btnisClicked) {
					judgePriceThread.start();
				} else {
					ActivityUtil.Toast(((MainActivity) context), "请等待处理完成",
							false, false);
				}
			}

		});
		/*
		 * 处理价格
		 */
		if (data.getIsRulingPrice() != null
				&& data.getIsRulingPrice().equals("1")) {
			holder.dishSPriceTv.setVisibility(View.GONE);
			holder.dishPriceTv.setText("￥" + data.getRulingPrice() + "/"
					+ data.getUnitName());
			holder.dishPriceTv.getPaint().setFlags(0);
		} else {
			if (data.getSpecialPrice() != null) {
				holder.dishSPriceTv.setVisibility(View.VISIBLE);
				holder.dishSPriceTv.setText(Html
						.fromHtml("<font color='red' type='bold'>" + "￥"
								+ data.getSpecialPrice() + "/份" + "</font>"));
				holder.dishPriceTv.setText("￥" + data.getPrice());
				holder.dishPriceTv.getPaint().setFlags(
						Paint.STRIKE_THRU_TEXT_FLAG);
			} else {
				holder.dishSPriceTv.setVisibility(View.GONE);
				holder.dishPriceTv.setText("￥" + data.getPrice() + "/"
						+ data.getUnitName());
				holder.dishPriceTv.getPaint().setFlags(0);
			}
		}
		/*
		 * 处理图标
		 */
		if (!data.getIsSpecialty().equals("null")) {
			holder.dishIconzpImv.setVisibility(View.VISIBLE);
			holder.dishIconzpImv.setBackgroundResource(drawable.zhaopai_big);
		} else {
			holder.dishIconzpImv.setVisibility(View.GONE);
		}

		if (!data.getIsRecommend().equals("null")) {
			holder.dishIcontjianImv.setVisibility(View.VISIBLE);
			holder.dishIcontjianImv.setBackgroundResource(drawable.tuijian_big);
		} else {
			holder.dishIcontjianImv.setVisibility(View.GONE);
		}

		if (data.getSpecialPrice() != null || data.getMemberPrice() != null) {
			holder.dishIcontjiaImv.setVisibility(View.VISIBLE);
			holder.dishIcontjiaImv.setBackgroundResource(drawable.tejia_big);
		} else {
			holder.dishIcontjiaImv.setVisibility(View.GONE);
		}

		if (data.getIsRulingPrice() != null
				&& data.getIsRulingPrice().equals("1")) {
			holder.dishIconsjImv.setVisibility(View.VISIBLE);
			holder.dishIconsjImv.setBackgroundResource(drawable.shijia_big);
		} else {
			holder.dishIconsjImv.setVisibility(View.GONE);
		}

		/*
		 * 处理估清菜肴
		 */
		if (data.getEstimate() != null && data.getEstimate() <= 0f) {
			holder.dishStopImv.setVisibility(View.VISIBLE);
			holder.dishCfBtn.setBackgroundDrawable(context.getResources()
					.getDrawable(R.drawable.laiyifen_on));
			holder.dishCfBtn.setEnabled(false);
		} else {
			holder.dishStopImv.setVisibility(View.INVISIBLE);
			holder.dishCfBtn.setBackgroundDrawable(context.getResources()
					.getDrawable(R.drawable.laiyifen));
			holder.dishCfBtn.setEnabled(true);
		}
		return convertView;
	}

	public List<Dish> getList() {
		return list;
	}

	public void setList(List<Dish> list, boolean isInvalidated) {
		this.list = list;
		notifyDataSetChanged();
		if (isInvalidated)
			notifyDataSetInvalidated();
	}

}

class Holder {
	RelativeLayout viewbg;
	RoundImageView image;
	RelativeLayout ly;
	TextView tv;
	Button dishCfBtn;
	TextView dishSPriceTv;
	TextView dishPriceTv;
	ImageView dishIconzpImv;
	ImageView dishIcontjianImv;
	ImageView dishIcontjiaImv;
	ImageView dishIconsjImv;
	ImageView dishStopImv;
	TextView dishOrderNumTv;
	ImageView rst_icon;
	TextView rst_tv;
}